//
//  LoginViewController.m
//  EasyToTesco
//
//  Created by mc on 16/2/25.
//  Copyright © 2016年 Jack. All rights reserved.
//

#import "LoginViewController.h"
#import "HeaderFileForEasyToTesco.h"

//数据请求
#import "AFNetworking.h"
#import "MessageReceiveViewController.h"


//忘记密码头问文件
#import "LostPasswordViewController.h"


//注册界面头文件
#import "RegisterViewController.h"

#define LoginMarc 40

@interface LoginViewController ()<UITextFieldDelegate, UIAlertViewDelegate, UITableViewDataSource, UITableViewDelegate>


@property (nonatomic, strong)UITableView *logintableview;

@property (nonatomic, strong)NSMutableDictionary *loginDic;

@property(nonatomic, strong)UITextField *UserName;
@property(nonatomic, strong)UITextField *PassWord;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.loginDic = [[NSMutableDictionary alloc] initWithCapacity:0];
    
    [self addLogintopviewUI];
    
//    [self addloginTableview];
    
    [self addLoginViewUI:self.view];
    

    
    
    
}

- (void)addloginTableview {
    self.logintableview = [[UITableView alloc] initWithFrame:CGRectMake(0, HIGHT, WEITH, HIGHT*0.1) style:UITableViewStyleGrouped];
    self.logintableview.scrollEnabled = NO;
    self.logintableview.dataSource = self;
    self.logintableview.delegate = self;
    self.logintableview.tableFooterView = [[UIView alloc] init];
    [self.view addSubview:self.logintableview];
}

- (void)addLogintopviewUI{
    
    UIImageView *image1 = [[UIImageView alloc] initWithFrame:CGRectMake(10, (self.secondView.frame.size.height-20)/2, 20, 20)];
    image1.image = [UIImage imageNamed:@"goback-icon.png"];
    [self.secondView addSubview:image1];
    self.leftBtn.hidden = YES;
    
    UIButton *goBackBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    goBackBtn.frame = CGRectMake(0, 0, self.secondView.frame.size.height, self.secondView.frame.size.height);
    [goBackBtn addTarget:self action:@selector(gobackClick) forControlEvents:UIControlEventTouchUpInside];
    [self.secondView addSubview:goBackBtn];
    self.titleLabel.text = @"登录";

}
- (void)gobackClick {
    [self dismissViewControllerAnimated:YES completion:nil];
}


-(void)addLoginViewUI:(UIView *)headerview {
    UIImageView *iconPic = [[UIImageView alloc] initWithFrame:CGRectMake((WEITH-100)/2, HIGHT*0.1+30, 100, 100)];
    iconPic.backgroundColor = [UIColor orangeColor];
    [headerview addSubview:iconPic];
    
    
    self.UserName = [[UITextField alloc] initWithFrame:CGRectMake(LoginMarc, CGRectGetMaxY(iconPic.frame)+30, WEITH-LoginMarc*2, 40)];
    _UserName.layer.borderWidth = 1;
    _UserName.layer.borderColor = [UIColor blackColor].CGColor;
    _UserName.layer.cornerRadius = 6;
    _UserName.layer.masksToBounds = YES;
    _UserName.placeholder = @"请输入手机号码";
    _UserName.keyboardType = UIKeyboardTypeNumberPad;
    _UserName.clearButtonMode = UITextFieldViewModeAlways;
    _UserName.font = [UIFont systemFontOfSize:14];
    _UserName.delegate = self;
    [headerview addSubview:_UserName];
    
    self.PassWord = [[UITextField alloc] initWithFrame:CGRectMake(LoginMarc, CGRectGetMaxY(_UserName.frame)+10, WEITH-LoginMarc*2, 40)];
    self.PassWord.layer.borderWidth = 1;
    self.PassWord.layer.borderColor = [UIColor blackColor].CGColor;
    self.PassWord.layer.cornerRadius = 6;
    self.PassWord.delegate = self;
    self.PassWord.layer.masksToBounds = YES;
    self.PassWord.placeholder = @"请输入密码";
    self.PassWord.font = [UIFont systemFontOfSize:14];
    self.PassWord.secureTextEntry = YES;
    self.PassWord.clearButtonMode = UITextFieldViewModeAlways;
   
    [headerview addSubview:self.PassWord];
    
    UILabel *lostLabel =[[ UILabel alloc] initWithFrame:CGRectMake(WEITH-100-LoginMarc, CGRectGetMaxY(self.PassWord.frame), 100, 20)];
    lostLabel.font = [UIFont systemFontOfSize:12];
    lostLabel.textAlignment = NSTextAlignmentRight;
    lostLabel.text = @"忘记密码?";
    lostLabel.textColor = [UIColor blackColor];
    [headerview addSubview:lostLabel];
    
    UIButton *lostPwdBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    lostPwdBtn.frame = CGRectMake(WEITH-100-LoginMarc, CGRectGetMaxY(self.PassWord.frame), 100, 30);
    
    [lostPwdBtn addTarget:self action:@selector(LostPwdBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [headerview addSubview:lostPwdBtn];
    
    
    
    
    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    loginBtn.frame = CGRectMake(LoginMarc, CGRectGetMaxY(lostPwdBtn.frame)+40, WEITH-LoginMarc*2, 40);
    [loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    loginBtn.backgroundColor = [UIColor colorWithRed:52/255. green:147/255. blue:225/255. alpha:1];
    [loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    loginBtn.layer.cornerRadius = 6;
    loginBtn.layer.masksToBounds = YES;
    loginBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    loginBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [loginBtn addTarget:self action:@selector(LoginBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [headerview addSubview:loginBtn];
    
    UILabel *registerLabel = [[UILabel alloc] initWithFrame:CGRectMake(LoginMarc, CGRectGetMaxY(loginBtn.frame)+5, LoginMarc*2, 20)];
    registerLabel.text = @"注册";
    registerLabel.font = [UIFont systemFontOfSize:12];
    registerLabel.textAlignment = NSTextAlignmentLeft;
    [headerview addSubview:registerLabel];
    
    
    UIButton *registerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    registerBtn.frame = CGRectMake(LoginMarc, CGRectGetMaxY(loginBtn.frame)+5, LoginMarc*2, 20);
    [registerBtn addTarget:self action:@selector(RegisterBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [headerview addSubview:registerBtn];
    
    UILabel *opinionLabel = [[UILabel alloc] initWithFrame:CGRectMake(WEITH-LoginMarc-LoginMarc*2, CGRectGetMaxY(loginBtn.frame)+5, LoginMarc*2, 20)];
    opinionLabel.text = @"意见反馈";
    opinionLabel.font = [UIFont systemFontOfSize:12];
    opinionLabel.textAlignment = NSTextAlignmentRight;
    [headerview addSubview:opinionLabel];
    
    
    UIButton *opinionBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    opinionBtn.frame = CGRectMake(WEITH-LoginMarc-LoginMarc*2, CGRectGetMaxY(loginBtn.frame)+5, LoginMarc*2, 20);
    [opinionBtn addTarget:self action:@selector(OpinionBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [headerview addSubview:opinionBtn];
    
}




//忘记密码按钮
- (void)LostPwdBtnClick:(id)sender {
    NSLog(@"忘记密码按钮的点击事件");
    
    LostPasswordViewController *lostPwdVc = [[LostPasswordViewController alloc] init];
    [self presentViewController:lostPwdVc animated:YES completion:nil];
}
//登录按钮
- (void)LoginBtnClick:(id)sender {
    NSLog(@"登录按钮");
     [self requestLoginDatasourse];
}

//注册按钮
- (void)RegisterBtnClick:(id)sender {
    RegisterViewController *registerVC = [[RegisterViewController alloc] init];
    
    [self presentViewController:registerVC animated:YES completion:nil];
}

//意见反馈按钮
- (void)OpinionBtnClick:(id)sender {
    MessageReceiveViewController *messageVC =[[MessageReceiveViewController alloc] init];
    [self presentViewController:messageVC animated:YES completion:nil];
}


#pragma mark -- UITextFieldDelegate
//触摸空白处回收键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.UserName resignFirstResponder];
    
    [self.PassWord resignFirstResponder];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField == self.UserName) {
        if (string.length == 0) return YES;
        
        NSInteger existedLength = textField.text.length;
        NSInteger selectedLength = range.length;
        NSInteger replaceLength = string.length;
        if (existedLength - selectedLength + replaceLength >= 12) {
            return NO;
        }
    }
   
    
    return YES;
}

//实时监控键盘的状态
- (void)textFieldDidChange:(UITextField *)textField
{
    if (textField == self.UserName) {
        if (textField.text.length >=12) {
            textField.text = [textField.text substringToIndex:12];
        }
    }
    
#pragma mark -- 在这里判断手机号码的归属地
//    if ([textField.text isEqualToString:@"123456"]) {
//        self.NumberInfo.text = @"归属地改变了";
//    }
    NSLog(@"当前----===:%@", textField.text);
}

<<<<<<< HEAD
=======



>>>>>>> dd1aac4040986135177ad18eb7781566439f59ee
#pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    return nil;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return HIGHT*0.9;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] init];
    headerView.userInteractionEnabled = YES;
    [self addLoginViewUI:headerView];
    
    return headerView;
}


#pragma mark --- 登陆页面数据加载
- (void)requestLoginDatasourse {
        AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    
   //18620614920
    
    NSString *username = self.UserName.text;
    NSString *password = self.PassWord.text;

    NSLog(@"%@--%@", username, password);
    
    NSDictionary *param = @{@"username":[NSString stringWithFormat:@"%@", username], @"password":[NSString stringWithFormat:@"%@", password]};
    
    __weak LoginViewController *loginSelf = self;
    
    [mgr POST:@"http://www.ylgw8.com/AppUser/CheckLogin" parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        
       
        NSLog(@"%@", string);

        self.loginDic = [loginSelf toArrayOrNSDictionary:responseObject];
        
        if ([[NSString stringWithFormat:@"%@", self.loginDic[@"code"]] isEqual:@"1"]) {
            UIAlertView *LoginAlview = [[UIAlertView alloc] initWithTitle:@"提示" message:@"登录成功, 返回" delegate:loginSelf cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            LoginAlview.tag = 1000;
            [LoginAlview show];
        } else {
            UIAlertView *LoginAlview = [[UIAlertView alloc] initWithTitle:@"" message:[NSString stringWithFormat:@"%@", self.loginDic[@"message"]] delegate:loginSelf cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            LoginAlview.tag = 1001;
            [LoginAlview show];
        }
                [self.logintableview reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation,NSError *error)
     {
         //         operation.response.statusCode;//404 401之类
//         NSLog(@"数据请求错误原因:%@", error);
//         NSLog(@"数据请求错误码:%ld", (long)operation.response.statusCode);
     }];
}

#pragma mark -- UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 1000) {
        
        //保存数据
        [self savelogindataToLocal];
        
        [self dismissViewControllerAnimated:YES completion:nil];
    } else {
        self.UserName.text = nil;
        self.PassWord.text = nil;
        [self.logintableview reloadData];
    }
    
    
}


// 将JSON串转化为字典或者数组
- (id)toArrayOrNSDictionary:(NSData *)jsonData{
    NSError *error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                    options:NSJSONReadingAllowFragments
                                                      error:&error];
    
    if (jsonObject != nil && error == nil){
        return jsonObject;
    }else{
        // 解析错误
        return nil;
    }
}

//存储数据到本地
- (void)savelogindataToLocal{
    
  
    
    //1. 创建一个plist文件
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *path=[paths objectAtIndex:0];
    NSLog(@"path = %@",path);
    NSString *filename=[path stringByAppendingPathComponent:@"loginData.plist"];
    //创建
    NSFileManager* fm = [NSFileManager defaultManager];
    [fm createFileAtPath:filename contents:nil attributes:nil];
    
    //NSDictionary* dic = [NSDictionary dictionaryWithContentsOfFile:plistPath];
    //创建一个dic，写到plist文件里
//    NSDictionary* dic = [NSDictionary dictionaryWithObjectsAndKeys:@"sina",@"1",@"163",@"2",nil];
//    [dic writeToFile:filename atomically:YES];
    
    [self.loginDic writeToFile:filename atomically:YES];
    
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
